//
//  UserSearchViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UserSearchViewController.h"
#import "User.h"
#import "ImageStore.h"
#import "FriendDetailViewController.h"


@implementation UserSearchViewController


#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/


- (id) initWithDelegate:(id)adelagate action:(SEL)act
{
    self = [super init];
	if ( self ) {
		delegate = adelagate;
		action = act;
	}
	return self;
}


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	// Create a search bar
	searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
	searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	searchBar.keyboardType = UIKeyboardTypeAlphabet;
	searchBar.placeholder = @"按昵称搜索";
	searchBar.delegate = self;
	searchBar.showsCancelButton = YES;
	
	self.tableView.tableHeaderView = searchBar;
	
	users = [[NSMutableArray alloc] initWithCapacity:0];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark searchBar Delegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar
{
	[asearchBar resignFirstResponder];
	
	if ( client ) return;
	client = [[TwitterClient alloc] initWithTarget:self action:@selector(didSearchUser:obj:)];
	[client searchUser:asearchBar.text];
}


- (void) didSearchUser:(TwitterClient*)sender obj:(id)obj
{
	client = nil;
	
	if ( sender.hasError ) {
		[sender alert];
		return;
	}
	
	if ( obj == nil || obj == [NSNull null] || ![obj isKindOfClass:[NSArray class]]) return;
	
	NSArray* arr = (NSArray*) obj;
	[users removeAllObjects];
	
	User* user = nil;
	for ( NSDictionary* dic in arr ) {
		if ( dic == nil || (id)dic == [NSNull null] || ![dic isKindOfClass:[NSDictionary class]] ) continue;
		user = [User userWithJsonDictionary:dic];
		[users addObject:user];
	}
	
	[self.tableView reloadData];
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)asearchBar
{
	[asearchBar resignFirstResponder];
}



#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [users count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"UserSearchViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

	User* user = [users objectAtIndex:indexPath.row];
    cell.textLabel.text = user.screenName;
	
	if ( user.profileImageUrl_s && [user.profileImageUrl_s length] > 0 ) {
		cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:user.profileImageUrl_s]]];
	}
	else {
		cell.imageView.image = [ImageStore defaultProfileImage:NO];
	}
	
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	if ( delegate && action ) {
		User* user = [users objectAtIndex:indexPath.row];
		[delegate performSelector:action withObject:user];
        [self.navigationController popViewControllerAnimated:YES];
	}
    else {
        
    }
}


- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
	User* user = [users objectAtIndex:indexPath.row];
	FriendDetailViewController* controller = [[FriendDetailViewController alloc] initWithUser:user];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	[searchBar release];
	[users release];
}


- (void)dealloc {
	[searchBar release];
	[users release];
    [super dealloc];
}


@end

